/**
 *
 *
 * props:
 *  data: 数据
 *  name: rowData[name] 返回列表数据
 *  onRowChange: (index) => {} 被选中的index
 *
 * method:
 *  setDataSource(data): 刷新数据
 *
 */

import React, { Component } from 'react';
import {
    View,
    ScrollView,
    StyleSheet,
    Platform,
    Dimensions
} from 'react-native';

import PropTypes from "prop-types";
import Color from "../../config/theme/standard/color";
import Label from '../label/index';


export default class Picker extends Component {


    constructor(props) {
        super(props);
        this._ScrollView = null;
        let data = props.data;
        this.onScrollCount = 0;
        this.state = {
            prevPropsData: data,
            data: data,
            prevPropsIndex: this.props.selectTo,
            index : this.props.selectTo
        };
    }

    _setDataSource(data) {
        if(this._ScrollView) {
            this._ScrollView.scrollTo({y: 0, animated: false});
        }
        this.setState({data: data});
    }

    _getItem() {
        if(this.state.data.length == 0) {
            return false;
        }
        let arr = this.state.data;
        let fontFamily = Platform.OS === 'ios' ? 'System' : 'Roboto';
        return arr.map((item, i) => {
            let colorTmp = null;
            let typeTmp = null;
            //let fontSizeTmp = [];
            // if(this.props.fontSize){
            //     fontSizeTmp.push({fontSize:this.props.fontSize});
            // }
            if(this.state.index == i){
                //colorTmp = 'black';
                colorTmp = Color.normal;
                typeTmp = 'button';
            }else{
                //textStyle.push({color:'#C0CBCB'});
               // colorTmp = 'description';
                colorTmp = Color.minor;
                typeTmp = 'form';
            }
            return (
                <View key={i} style={styles.item}>
                    {
                        this.props.type == "combobox" ? (
                            <Label text={this.props.name ? item[this.props.name] : item} type={typeTmp} color={colorTmp} textAlign={'center'} labelStyle={[{width:Dimensions.get('window').width}]} numberOfLines={this.props.numberOfLines} adjustsFontSizeToFit={this.props.adjustsFontSizeToFit} fontFamily={fontFamily}/>
                        ) :(
                            <Label text={this.props.name ? item[this.props.name] : item} type={typeTmp} color={colorTmp} textAlign={'center'}  numberOfLines={this.props.numberOfLines} adjustsFontSizeToFit={this.props.adjustsFontSizeToFit} fontFamily={fontFamily}/>
                        )
                    }
                </View>
            )
        })
    }

    _onScrollEndDrag(e) {
        let y = e.nativeEvent.contentOffset.y;
        let onScrollEndDragCount = this.onScrollCount;
        let start = Date.now();
        if(this.fixInterval) {
            clearInterval(this.fixInterval);
        }
        this.fixInterval = setInterval(() => this._timeFix(start, y, onScrollEndDragCount),10);
    }

    _timeFix(start, y, onScrollEndDragCount) {
        let now = Date.now();
        let end = 200;
        if(now - start > end) {
            clearInterval(this.fixInterval);
            if(onScrollEndDragCount == this.onScrollCount) {
                this._onScrollEnd(y);
            }
            this._onScrollEnd(y);
        }
    }

    _onMomentumScrollEnd(e) {
        let y = e.nativeEvent.contentOffset.y;
        this._onScrollEnd(y);
    }

    _onScroll(e) {
        this.onScrollCount++;
        let y = e.nativeEvent.contentOffset.y;
        if((Platform.OS) == 'web'){
            let onScrollEndDragCount = this.onScrollCount;
            let start = Date.now();
            if(this.fixInterval) {
                clearInterval(this.fixInterval);
            }
            this.fixInterval = setInterval(() => this._timeFix(start, y, onScrollEndDragCount),10);
        }
    }

    _onScrollEnd(y) {
        let y1 = y-(y%30);
        if(y%30 > 15) {y1 = y1+30;}
        let index = y1/30;
        if(this._ScrollView) {
            this._ScrollView.scrollTo({y: y1, animated: false});
        }
        if (typeof(this.props.onRowChange) === 'function') {
            this.props.onRowChange(index);
        }
        this.setState({
            index : index
        })
    }

    _selectTo() {
        let y = this.state.index*30;
        if(this._ScrollView) {
            this._ScrollView.scrollTo({y: y, animated: false});
        }
    }

    componentDidUpdate() {
        if(this.props.selectTo != null) {
            setTimeout(
                () => {
                    this._selectTo(this.props.selectTo)
                },0
            )
        }
    }

    // componentWillReceiveProps(nextProps) {
    //     this.setState({
    //         data: nextProps.data,
    //         index : nextProps.selectTo
    //     });
    // }

    static getDerivedStateFromProps(nextProps, prevState) {
        let dataFlag = false;
        let indexFlag = false;

        if (('data' in nextProps) && (nextProps.data !== prevState.prevPropsData)) {
            dataFlag = true;
        }
        
        if(('selectTo' in nextProps) && (nextProps.selectTo !== prevState.prevPropsIndex)){
            indexFlag = true;
        }
        if(dataFlag && indexFlag){
            return {
                prevPropsData: nextProps.data,
                data: nextProps.data,
                prevPropsIndex: nextProps.selectTo,
                index: nextProps.selectTo
            }
        }else{
            if(dataFlag){
                return {
                    prevPropsData: nextProps.data,
                    data: nextProps.data
                }
            }else if(indexFlag){
                return {
                    prevPropsIndex: nextProps.selectTo,
                    index: nextProps.selectTo
                }
            }
        }
        return null;
    }

    componentWillUnmount() {
        if(this.fixInterval) {
            clearInterval(this.fixInterval);
        }
    }


    render() {
        return (
            <View style = {{flex: 1}}>
                <View style = {styles.container}>
                    <ScrollView
                        bounces = {false}
                        onScrollEndDrag = {(e) => {this._onScrollEndDrag(e)}}
                        // onMomentumScrollEnd = {(e) => {this._onMomentumScrollEnd(e)}}
                        onScroll = {(e) => {this._onScroll(e)}}
                        scrollEventThrottle = {16}
                        showsVerticalScrollIndicator = {false}
                        ref = {(e) => this._ScrollView = e}
                        scrollEnabled = {this.props.enable}
                        onLayout = {() => this._selectTo()}
                    >
                        <View style = {styles.view} />
                        {this._getItem()}
                        <View style = {styles.view} />
                    </ScrollView>
                </View>
                <View style = {styles.show} pointerEvents = 'none' >
                </View>
            </View>
        )
    }
}
Picker.propTypes = {
    data: PropTypes.array,
    name: PropTypes.string,
    onRowChange: PropTypes.func,
    selectTo: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    enable:PropTypes.bool,
    fontSize:PropTypes.number,
    numberOfLines: PropTypes.number,
    adjustsFontSizeToFit:PropTypes.bool,
};
Picker.defaultProps = {
    selectTo:0,
    enable:true,
    adjustsFontSizeToFit:false,
    type:''
};
const styles = StyleSheet.create({
    container:{
        height: 216,
        backgroundColor: Color.white
    },
    view: {
        height:90
    },
    item:{
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
    },
    show:{
        height: 32,
        marginTop: -127,
        backgroundColor: Color.transparent,
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:Color.border
    }
});
